package com.ovhoo.android.smsbombing;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.telephony.gsm.SmsManager;
import android.view.Menu;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;


public class SendingThread extends Thread {
	
	private boolean running = false;
	private int nbSMSEnvoyees = 0;
	private Smsbombing activity;
	private ShortMessage message;
	private Handler handler;
	private static int period = 10000;
	private static final int defaultPeriod = 10000;
	
	
	public SendingThread(Smsbombing ctx, ShortMessage message, Handler handler){
		this.activity = ctx;
		this.message = message;
		this.handler = handler;
		


		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this.activity);
		SendingThread.period = Integer.parseInt(sp.getString("DIALOG_PREF_PERIOD","0"));
		if (SendingThread.period == 0){
			SendingThread.period = SendingThread.defaultPeriod;
		}
		else{
			SendingThread.period *= 1000;
		}
		
    }
	
	public void run(){
		
		while (true){
			
			if (this.running){
				this.envoyerSMS();
				this.nbSMSEnvoyees += 1;
			}
			
			try {
				Thread.sleep(SendingThread.period);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
	}
	
	
	public void start() {
		super.start();
		this.running = true;
		
	} 
	
	public void pause() {
		this.running = false;
		this.stop();
		
	} 
	

    private void envoyerSMS()
    {        
        PendingIntent intent = PendingIntent.getActivity(this.activity, 0, new Intent(this.activity, Smsbombing.class), 0);                
        SmsManager shortMessage = SmsManager.getDefault();
        shortMessage.sendTextMessage(this.message.getDestinator(), null, this.message.getMessage(), intent, null); 
        this.message.incrCounter();
        this.handler.obtainMessage().sendToTarget();
    } 
    
    
}
